package mosync.mobilelualiveserver;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Class that holds classes used for messaging.
 */
public class Messaging
{
	/**
	 * Class that represents a message.
	 */
	public static class Message implements Serializable
	{
		private static final long serialVersionUID = 8756931383296135605L;
		
		String mMessage;
		Object mObject;
		
		public Message(String message, Object object)
		{
			mMessage = message;
			mObject = object;
		}
		
		public String getMessage()
		{
			return mMessage;
		}
		
		public Object getObject()
		{
			return mObject;
		}
	}

	/**
	 * Thread that has two input channels and two output channels
	 * (two queues and two streams).
	 */
	@SuppressWarnings("unused")
	public static class MessageThread extends Thread
	{
		private MessageQueue mInQueue;
		private MessageQueue mOutQueue;
		private InputStream mInStream;
		private OutputStream mOutStream;
		
		public MessageThread(
			MessageQueue inQueue,
			MessageQueue outQueue,
			InputStream inStream,
			OutputStream outStream)
		{
			mInQueue = inQueue;
			mOutQueue = outQueue;
			mInStream = inStream;
			mOutStream = outStream;
		}
		
		public Message waitForMessage()
		{
			return mInQueue.nextMessage();
		}
	}

	/**
	 * Class that implements a thread safe message queue.
	 */
	@SuppressWarnings("unchecked")
	public static class MessageQueue
	{
		private LinkedBlockingQueue mMessageQueue = new LinkedBlockingQueue();
		
		public void postMessage(Message message)
		{
			mMessageQueue.offer(message);
		}
		
		public Message nextMessage()
		{
			try 
			{
				return (Message) mMessageQueue.take();
			} 
			catch (InterruptedException e) 
			{
				return null;
			}
		}
	}
}
